<template>
    <div style="height: 60px;background-color: #fff;padding: 10px 20px;box-sizing: border-box">
        <span style="line-height: 60px;font-size: 20px">分店地图</span>
        <el-button @click="router.push('/branch')" type="primary" style="float: right;margin-top: 15px">返回</el-button>
    </div>
    <div id="map_container" style="height:calc(100% - 60px) ;width: 100%">

    </div>
    <el-dialog :before-close="close_dialog" title="分店信息" v-model="dialog_branch">
        <el-form label-position="left" label-width="auto" :model="branch" :rules="rules" ref="form_branch">
            <el-form-item label="分店详细地址">
                <el-input readonly v-model="branch.address"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="分店名称">
                <el-input placeholder="请输入分店名称" v-model="branch.name"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="营业开始时间" >
                <el-time-picker placeholder="请选择" v-model="branch.workTimeStart" value-format="HH:mm:ss"></el-time-picker>
            </el-form-item>
            <el-form-item prop="name" label="营业结束时间">
                <el-time-picker placeholder="请选择" v-model="branch.workTimeEnd" value-format="HH:mm:ss"></el-time-picker>
            </el-form-item>
            <el-form-item prop="name" label="电话">
                <el-input placeholder="请输入电话" v-model="branch.phone"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="分店描述">
                <el-input maxlength="100" show-word-limit type="textarea" placeholder="请输入" v-model="branch.description"></el-input>
            </el-form-item>
            <el-form-item label="上传图片">
                <el-upload
                    v-model:file-list="fileList"
                    v-model:action="actionUrl"
                    name="file"
                    limit="1"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :class="{hide:hideUpload}"
                >
                    <el-icon>
                        <Plus/>
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialog_img">
                    <img style="width: 300px" w-full :src="dialogImageUrl"/>
                </el-dialog>
            </el-form-item>

        </el-form>
        <template #footer>
            <el-button @click="close_dialog">取消</el-button>
            <el-button @click="save_branch">确定</el-button>

        </template>
    </el-dialog>
</template>

<script setup>

import router from "@/router";
import {nextTick, onMounted, ref, watch} from "vue";
import { DrawScene, DrawControl ,OperateEventType} from 'bmap-draw';
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";


var map
//8)分店
const branch = ref({name:'',address:'', position:{},imgUrl:'',phone:'',workStartTime:'',workEndTime:'',description:''})
const dialog_branch = ref(false)

//当前位置经纬度
var local_point
//当前位置标记
var local_mk

var myIcon = new BMapGL.Icon("/imgs/icon/my_location2.svg", new BMapGL.Size(35, 40));
function get_location_me(){
    var geolocation = new BMapGL.Geolocation();
    geolocation.getCurrentPosition(function(r){
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            map.clearOverlays(local_mk)
            local_mk = new BMapGL.Marker(r.point,{icon:myIcon});
            local_mk.disableMassClear();//禁止覆盖物在map.clearOverlays方法中被清除
            map.addOverlay(local_mk);
            map.panTo(r.point);
            local_point = new BMapGL.Point(r.point.lng,r.point.lat)
            map.centerAndZoom(local_point,18)//设置中心点和缩放级别
            //map.setHeading(64.5);   //设置地图旋转角度
            map.setTilt(45);       //设置地图的倾斜角度

        }
        else {
            //alert('当前位置信息获取失败' + this.getStatus());
        }
    });

}

//进入页面立即执行
onMounted(()=>{
    //表示在DOM更新完毕后在执行，保证在存放地图的div创建完毕后在执行
    nextTick(()=>{
        //第七步：创建地图实例（注意不要导入）
        map = new BMapGL.Map("map_container")
        get_location_me()
        map.enableScrollWheelZoom();//启用滚轮放大缩小

        //添加控件
        let scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
        map.addControl(scaleCtrl);
        let zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
        map.addControl(zoomCtrl);
        let cityCtrl = new BMapGL.CityListControl();  // 添加城市列表控件
        map.addControl(cityCtrl);


        // 添加鼠标绘制控件
        //1)创建绘制场景类,本类为所有鼠标绘制控件的基类,必须先创建DrawScene类实例,注意:需要导入!
        const scene = new DrawScene(map);
        //2)在当前绘制场景下，创建绘制控件类（需要导入）
        const drawContrl = new DrawControl(scene, {
            //3)绘制控件配置项
            //3.1不显示对应绘制项的文字提示
            enableTips: false,
            //3.2设置当前绘制控件的位置（左上）
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            //3.3设置绘制控件显示哪些绘制项 circle圆形，rectangle矩形，Marker点
            drawingItems: [
                'marker'
            ]
        });

        //5)监听绘制完成事件，用户点击对勾时返回触发事件的对象
        scene.addEventListener(OperateEventType.COMPLETE,(event)=>{
            dialog_branch.value=true
            console.log(event.target)//触发事件的目标对象，即圆形、矩形或点
            //6)获取触发事件对象中的overlay值，overlay代表的是覆盖物
            let overlay = event.target.overlay;
            console.log(event)
            //7)判断当前绘制的图形
            if(overlay instanceof BMapGL.Marker){
                branch.value.position.type='marker'//点
                let latitude=overlay.latLng.lat//纬度
                let longitude=overlay.latLng.lng//经度
                console.log(latitude,typeof latitude)
                branch.value.position.recPoints=longitude+','+latitude//经度,纬度
                console.log(branch.value.position.recPoints)
                //记录当前点
                let point_choose = new BMapGL.Point(longitude,latitude)
                //根据坐标点获得该地点的地址描述(逆地址解析)
                    //创建地理编码实例
                var myGeo = new BMapGL.Geocoder();
                    //根据坐标得到地址描述
                myGeo.getLocation(point_choose, function(result){
                    if (result){
                        //alert('当前选择的地址为'+result.address);
                        ElMessage({
                            showClose:'true',
                            message: '当前选择的分店地址为：'+result.address,
                            type: 'success',
                        })
                        branch.value.address=result.address
                    }
                });
            }
        })

        //4)将绘制控件添加到地图上
        map.addControl(drawContrl);

    })
})
const save_branch=()=>{
    form_branch.value.validate((valid)=>{
        if(!valid){
            ElMessage.error('请检查输入的信息')
        }else{
            //上传的图片地址
            if(fileList.value.length!==0){
                branch.value.imgUrl=fileList.value[0].response.data
            }

            //console.log(branch.value)
            branch.value.position=JSON.stringify(branch.value.position)//{"type":"marker","recPoints":"116.39602745224354,39.90608090175648"}
            let data = qs.stringify(branch.value)
            console.log(data)
            axios.post(BASE_URL+'/v1/branch/save',data)
                .then((response)=>{
                    if(response.data.code===2000){
                        ElMessage.success('添加成功')
                        dialog_branch.value=false
                        branch.value={name:'',address:'', position:{},imgUrl:'',phone:'',workStartTime:'',workEndTime:'',description:''}
                        map.clearOverlays()
                        router.push('/branch')
                    }else{
                        ElMessage.error(response.data.msg)
                    }
                })
        }
    })
}

/*图片上传组件开始*/
const fileList = ref([])
const dialogImageUrl=ref('')
const dialog_img=ref(false)
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
    //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
    let imgUrl = uploadFile.response.data;
    //2.给后端发请求,删除图片
    axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
        .then((response)=>{
            if (response.data.code===2000){
                ElMessage.success('删除成功!');
            }
        })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
    //uploadFile就是刚上传那个图片文件对象
    dialogImageUrl.value = uploadFile.url
    //dialogImageUrl.value = BASE_URL+uploadFile.response.data
    dialog_img.value = true;
    //console.log(fileList.value[0].response.data);//后端响应过来的图片路径  /2024/10/26/310dae46-98d5-4f69-a87f-14a733e30898.png
}
//上传后不显示上传按钮
const hideUpload = ref(false)
watch(() =>fileList.value.length,(newValue,oldValue)=> {
    //console.log('watch',newValue);
    if(newValue===1){
        hideUpload.value=true//隐藏上传按钮
    }else{
        hideUpload.value=false//显示
    }
},{ immediate: false }/*初始化时不触发*/)
/**图片上传相关代码结束**/

const close_dialog = ()=>{
    ElMessageBox.confirm('确认要关闭吗')
        .then(() => {
            //如果上传了图片但没有确认，点了取消按钮，删除上传的图片
            if(fileList.value.length>0){
                let upload_img_url = fileList.value[0].response.data
                axios.post(BASE_URL+'/v1/file/remove?imgUrl='+upload_img_url)
                    .then((response)=>{
                        if (response.data.code===2000){
                            ElMessage.warning('图片取消保存');
                        }
                    })
            }
            dialog_branch.value=false
            branch.value={name:'',address:'', position:{},imgUrl:'',phone:'',workStartTime:'',workEndTime:'',description:''}
            map.clearOverlays()
            // 清除表单验证状态，可选链操作符：?. 来确保在 formRef 未定义时不会抛出错误。
            form_branch.value?.resetFields();
            form_branch.value?.clearValidate();
        }).catch(() => {

        })
    /*if(confirm('确认要关闭吗')){
        dialog_branch.value=false
        branch.value={name:'',address:'', position:{},imgUrl:''}
        map.clearOverlays()
    }*/
}
const form_branch = ref(null)
const rules={
    name:[
        {required:true,message:'必填项',trigger:'blur'}
    ]
}

</script>

<style>
.hide .el-upload--picture-card {
    display: none;
}
</style>